import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import { createStore } from 'vuex'
import './assets/css/base.less'
import axios from 'axios'
import qs from "qs"
import { API_BASE_URL } from './config/index'

// 导入Element Plus
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'

// 导入Element Plus图标
import ElementIcons from './plugins/element-icons'

// 创建Vuex Store
const store = createStore({
  state() {
    return {}
  }
})

// 设置axios默认配置
axios.defaults.baseURL = 'http://localhost:9000'

// 请求拦截器，为每个请求添加token
axios.interceptors.request.use(
  config => {
    const token = localStorage.getItem('access-token')
    if (token) {
      // 将token添加到请求头，添加Bearer前缀
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器，处理token过期等情况
axios.interceptors.response.use(
  response => {
    return response
  },
  error => {
    if (error.response && error.response.status === 401) {
      // token过期或无效，清除本地存储并跳转到首页
      localStorage.removeItem('access-token')
      localStorage.removeItem('user')
      router.push('/')
    }
    return Promise.reject(error)
  }
)

// 创建应用实例
const app = createApp(App)

// 全局配置
app.config.globalProperties.$axios = axios
app.config.globalProperties.$qs = qs

// 全局错误处理
app.config.errorHandler = (err, vm, info) => {
  console.error('Vue Error:', err, info)
}

// 使用插件
app.use(router)
app.use(store)
app.use(ElementPlus, {
  locale: zhCn
})
app.use(ElementIcons)

// 挂载应用
app.mount('#app')
